(function($, api) {
    // 常规配置
    var appflag = '$demoapp_'; // 应用标识
    var path = '';
    var paths = '';
    var themeColor = '#06C1AE'; // rgb(6, 193, 174)

    api.getPath = function () {
    	return path;
    }

    api.getPaths = function () {
    	return paths;
    }

    api.getThemeColor = function () {
    	return themeColor;
    }

    // 后台接口url配置
    var urls = {
        login: '/user/login', // 登录
        register: '/user/register', // 注册
        forgetPwd: '/user/forgetPwd' // 忘记密码
    }

    // 通过key获取url
    api.getURL = function(key) {
        return path + urls[key];
    }

    var owfn = $.openWindow;
    // 重写openWindow
    $.openWindow = function (config) {
    	owfn($.extend({}, {
	        show: {
	            aniShow: 'pop-in', // slide-in-right/bottom/left/top fade-in zoom-out zoom-fade-out pop-in
	            duration: 200
	        },
	        styles: {
	            // popGesture: 'none',
                scrollIndicator: 'none',
                errorPage: '_wwww/404.html'
	        },
	        waiting: {
	            autoShow: false
	        }
    	}, config));
    }

    // 判断是否支持沉浸式状态栏，并返回状态栏高度 plus.navigator.isImmersedStatusbar()
    api.immersion = function(callback) {
        var immersed = 0;
        var ms = (/Html5Plus\/.+\s\(.*(Immersed\/(\d+\.?\d*).*)\)/gi).exec(navigator.userAgent);
        if (ms && ms.length >= 3) {
            immersed = parseFloat(ms[2]);
        }
        if (immersed) {
	        var v1 = immersed;
	        var v2 = v1 + 44;
	        var styleStr = '.immersion.mui-bar.mui-bar-nav,.immersion .mui-bar.mui-bar-nav,.immersion .mui-navbar{padding-top:' + v1 + 'px;height:' + v2 + 'px;}.immersion.mui-bar-nav~.mui-content{padding-top:' + v2 + 'px;}.immersion .mui-pages{top:' + v2 + 'px}';
	        var tag = document.querySelector('style');
	        if (tag) {
	            tag.innerHTML = tag.innerHTML + styleStr;
	        } else {
	            tag = document.createElement('style');
	            tag.style = 'text/css';
	            tag.innerHTML = styleStr;
	            document.head.appendChild(tag);
	        }
	        callback && callback.call(this, immersed);
        }
    }

    // get ls.$state
    api.getState = function() {
        var stateText = localStorage.getItem(appflag + 'state') || '{}';
        return JSON.parse(stateText);
    }

    // set ls.$state
    api.setState = function(state) {
        state = state || {};
        localStorage.setItem(appflag + 'state', JSON.stringify(state));
    }

    var checkEmail = function(email) {
        email = email || '';
        return (email.length > 3 && email.indexOf('@') > -1);
    }

    // get ls.$settings
    api.getSettings = function() {
        var settingsText = localStorage.getItem(appflag + 'settings') || '{}';
        return JSON.parse(settingsText);
    }

    // set ls.$settings
    api.setSettings = function(settings) {
        settings = settings || {};
        localStorage.setItem(appflag + 'settings', JSON.stringify(settings));
    }

    // 获取本地是否安装客户端
    api.isInstalled = function(id) {
        if (id === 'qihoo' && $.os.plus) {
            return true;
        }
        if ($.os.android) {
            var main = plus.android.runtimeMainActivity();
            var packageManager = main.getPackageManager();
            var PackageManager = plus.android.importClass(packageManager)
            var packageName = {
                'qq': 'com.tencent.mobileqq',
                'weixin': 'com.tencent.mm',
                'sinaweibo': 'com.sina.weibo'
            }
            try {
                return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
            } catch (e) {}
        } else {
            switch (id) {
                case 'qq':
                    var TencentOAuth = plus.ios.import('TencentOAuth');
                    return TencentOAuth.iphoneQQInstalled();
                case 'weixin':
                    var WXApi = plus.ios.import('WXApi');
                    return WXApi.isWXAppInstalled()
                case 'sinaweibo':
                    var SinaAPI = plus.ios.import('WeiboSDK');
                    return SinaAPI.isWeiboAppInstalled()
                default:
                    break;
            }
        }
    }

    window.$get = function(id) {
        return document.getElementById(id);
    }

    // domObj.on('tap', fn)
    HTMLElement.prototype.on = function(eventType, callback) {
        var me = this;
        me._listeners = me._listeners || {};
        me._listeners[eventType] = callback;
        me.addEventListener(eventType, callback, false);
        return me;
    }

    // domObj.off('tap')
    HTMLElement.prototype.off = function(eventType) {
        var me = this;
        me._listeners = me._listeners || {};
        if (typeof me._listeners[eventType] === 'function') {
            me.removeEventListener(eventType, me._listeners[eventType]);
            delete me._listeners[eventType];
        }
        return me;
    }

    // domObj.trigger('tap')
    HTMLElement.prototype.trigger = function(eventType) {
        var evt = document.createEvent('HTMLEvents');
        evt.initEvent(eventType, true, true);
        this.dispatchEvent(evt);
        return this;
    }

    // 获取地址栏参数对象
    api.param = (function() {
        var obj = {};
        var list = location.search.substring(1).split('&');
        var len = list.length;
        var i = 0;
        for (; i < len; i++) {
            var arr = list[i].split('=');
            obj[arr[0]] = arr[1];
        }
        return obj;
    })();

    // 判断是否为网页
    api.isWeb = function() {
        return !$.os.android && !$.os.ios;
        return localStorage.getItem(appflag + 'guide') == null;
    }

    // 让web也能够执行plusReady
    if (api.isWeb()) {
        $.plusReady = function(callback) {
            callback();
        }
    }

	var requestStack = [];
    // ajax请求、或get请求
    api.get = api.ajax = function(param, data, done, fail) {
    	requestStack.push(1);
        if (typeof data === 'function') {
            fail = done;
            done = data;
            data = {};
        }
        if (typeof param === 'string') {
            param = {
                url: this.getURL(param),
                data: data,
                success: done,
                error: fail
            }
        }
        var plusReady = typeof plus != 'undefined';
        plusReady && plus.nativeUI.showWaiting();
        $.ajax({
            url: param.url,
            type: param.type || 'get',
            data: param.data || {},
            dataType: 'json',
            timeout: param.timeout || 10000,
            // headers: {'Content-Type': 'application/json'},
            success: function(ret) {
                if (!ret.success) {
                    $.alert(ret.msg);
                    param.success && param.success.call(this);
                    return;
                }
                param.success && param.success.call(this, ret.data || {});
            },
            error: function(e) {
                $.alert('请求出错啦：\n' + param.url);
                param.error && param.error.call(this, e);
            },
            complete: function() {
            	requestStack.pop();
            	if (!requestStack.length && plusReady) {
	                plus.nativeUI.closeWaiting();
            	}
            }
        });
    }

    // post请求
    api.post = function(key, data, done, fail) {
        if (typeof data === 'function') {
            fail = done;
            done = data;
            data = {};
        }
        this.ajax({
            url: this.getURL(key),
            type: 'post',
            data: data,
            success: done,
            error: fail
        });
    }

    // 双击退出
    api.doubletapExit = function() {
        $.oldBack = $.back;
        var press = 0;
        $.back = function() {
            press++;
            if (press > 1) {
                plus.runtime.quit();
            } else {
                plus.nativeUI.toast('再按一次退出应用');
            }
            setTimeout(function() {
                press = 0;
            }, 1000);
            return false;
        }
    }

    var olpage;
    function getolweb () {
        if (!olpage) {
            olpage = plus.webview.getWebviewById('outerlink');
        }
        return olpage;
    }

    api.skip = function (title, viewurl, weburl) {
        $.fire(getolweb(), 'show', {
            title: title,
            url: encodeURIComponent(viewurl)
        });
        setTimeout(function () {
            $.openWindow({
                id: 'outerlink',
                url: weburl
            });
        }, 10);
    }
})(mui, window.app = {});